const { connection } = require("../base/connect");
const { throwError } = require("../base/error");
const { sendData } = require("../base/success");
module.exports = async (ctx) => {
  const collection = (await connection).collection("provinces");
  const province =
    typeof ctx.query["province"] === "undefined" ? "" : ctx.query["province"];
  const city =
    typeof ctx.query["city"] === "undefined" ? "" : ctx.query["city"];
  let result = new Object();
  if (!(province || city)) {
    //获取各省部分数据和经纬度
    result = await collection
      .find({}, { projection: { _id: 0, dangerAreas: 0, statisticsData: 0 } })
      .toArray();
  } else if (province && !city) {
    result = await collection
      .find(
        // 查询条件
        { $or: [{ provinceName: province }, { provinceShortName: province }] },
        { projection: { statisticsData: 0, _id: 0 } }
      )
      .toArray();
    if (!result.length) {
      throwError(ctx, 0, "地区不存在~");
      return;
    }
  } else if (!province && city) {
    const temp = await collection
      .find({}, { projection: { statisticsData: 0, _id: 0 } })
      .toArray();
    for (let j = 0; j < temp.length; j++) {
      for (let i = 0; i < temp[j].cities.length; i++) {
        // 跳过省直接查找城市
        if (temp[j].cities[i].cityName == city) {
          result = temp[j].cities[i];
          result["provinceName"] = temp[j].provinceName;
          break;
        }
        if (JSON.stringify(result) != "{}") break;
      }
    }
    if (JSON.stringify(result) == "{}") {
      throwError(ctx, 0, "地区不存在~");
      return;
    }
  } else {
    const temp = await collection
      .find(
        { $or: [{ provinceName: province }, { provinceShortName: province }] },
        { projection: { statisticsData: 0 } }
      )
      .toArray();
    // 遍历查找城市
    const citiesList = temp[0].cities;
    for (let i = 0; i < citiesList.length; i++) {
      if (citiesList[i].cityName === city) {
        result = citiesList[i];
      }
    }
    if (JSON.stringify(result) == "{}") {
      throwError(ctx, 0, "地区不存在~");
      return;
    }
  }
  sendData(ctx, result);
};
